package com.randis.dailyplanner.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.randis.dailyplanner.ServiceLocator;
import com.randis.dailyplanner.dao.UserDao;
import com.randis.dailyplanner.managers.UserManager;

public class AuthenticationFilter implements Filter {

	private UserDao 	userDao 	= ServiceLocator.getInstance().getUserDao();
	
	private UserManager userManager = ServiceLocator.getInstance().getUserManager();
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(	ServletRequest 	request, 
							ServletResponse response,
							FilterChain 	chain) throws IOException, ServletException {
        
        HttpServletRequest  httpRequest 	= (HttpServletRequest)request;
        HttpServletResponse httpResponse    = (HttpServletResponse)response;

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        
        String requestURI = httpRequest.getRequestURI();
        
        if (user == null &&
        	requestURI.indexOf("/login") == -1 &&
        	requestURI.indexOf("/admin") == -1) {
        	httpResponse.sendRedirect(userService.createLoginURL(httpRequest.getRequestURI()));
        	return;
        }
        
        if (user != null) {
        	createUserIfNecessary(user);
	        com.randis.dailyplanner.domain.User userObject = userDao.findUser(user.getNickname());
	        userManager.setCurrentUser(userObject);
        }
        
        chain.doFilter(request, response);

        if (user != null) {
        	userManager.clearCurrentUser();
        }
	}

	private void createUserIfNecessary(User user) {
		com.randis.dailyplanner.domain.User userObject = userDao.findUser(user.getNickname());
		if (userObject == null) {
			userObject = new com.randis.dailyplanner.domain.User();
			userObject.setLogin(user.getNickname());
			userObject.setEmail(user.getEmail());
			userDao.saveUser(userObject);
		}
			
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
	}
}
